<?php
//判断是否已经登录,是则回到首页,防止一些人手贱
if (isset($_SESSION['username'], $_SESSION['password']))
{
    echo '<script>alert("你已成功登录,无需重复登录");location.href="index.php";</script>';
}
?>
<div id="carbonForm" style="margin-top: 60px;">
    <h1>登录</h1>
    <form method="post">
        <fieldset>

            <div class="formRow">
                <div class="label">
                    <label for="name">用户名:</label>
                </div>
                <div class="field">
                    <input type="text" name="username">
                </div>
            </div>

            <div class="formRow">
                <div class="label">
                    <label for="pass">密码:</label>
                </div>
                <div class="field">
                    <input type="password" name="password">
                </div>
            </div>

            <div class="formRow">
                <div class="label">
                    <label for="name">验证码:</label>
                </div>
                <div class="field">
                    <input type="text" name="validcode">
                </div>
            </div>

            <div class="formRow">
                <div class="field" style="float: right">
                    <img src="./config/validcode.php" width="200" height="50" />
                </div>
            </div>
        </fieldset>
        <div class="signupButton">
            <input type="submit" name="btnLogin" id="submit">
        </div>
    </form>
</div>
<?php
//连接数据库初始化
include 'config/DB.php';
$connection = new DB();
if (isset($_POST['btnLogin']))
{
    $username = $_POST['username'];
    $password = $_POST['password'];
    $validcode = $_POST['validcode'];
    if ($username == '' || $password == '')
    {
        echo '<script language="javascript">alert("用户名或密码不能为空!");</script>';
        return;
    }elseif (md5($validcode)!=$_SESSION['validcode'])
    {
        echo '<script language="javascript">alert("验证码错误,请重试!");</script>';
        return;
    }
    $result = $connection->query("SELECT * FROM user WHERE username='"
            . $username
            . "'AND password='"
            . md5($password) . "'");
    if ($connection->num_rows($result) > 0)
    {
        $_SESSION['username'] = $username;
        $_SESSION['password'] = md5($password);
        echo '<script language="javascript">alert("登陆成功");location.href="index.php";</script>';
    } else
    {
        echo '<script language="javascript">alert("登陆失败,请检查用户名或密码是否正确");</script>';
    }
}
?>
